﻿using System;
using System.Collections.Generic;
using System.Text;
using WTest.Model;
using System.Text.RegularExpressions;
using DaiChong.Lib.Http;
using System.Windows.Forms;
using System.Threading;

namespace WTest
{
    public class AsyncLetv : AsyncBase
    {
        public string SiteName { get; set; }

        protected override void AsyncWork()
        {
            #region 最新...[删]
            /*
            var lst_1 = new Dictionary<string, MovieType>
            {
                {"http://so.letv.com/list/c1_t9_a-1_y-1_f_at_o1_p.html", MovieType.喜剧片},
                {"http://so.letv.com/list/c1_t10_a-1_y-1_f_at_o1_p.html" , MovieType.动作片},
                {"http://so.letv.com/list/c1_t11_a-1_y-1_f_at_o1_p.html" ,MovieType.爱情片},
                {"http://so.letv.com/list/c1_t12_a-1_y-1_f_at_o1_p.html" ,MovieType.恐怖片},
                {"http://so.letv.com/list/c1_t17_a-1_y-1_f_at_o1_p.html" ,MovieType.科幻片},
                {"http://so.letv.com/list/c1_t14_a-1_y-1_f_at_o1_p.html" ,MovieType.战争片},
                {"http://so.letv.com/list/c1_t18_a-1_y-1_f_at_o1_p.html" ,MovieType.动作片},
                {"http://so.letv.com/list/c1_t16_a-1_y-1_f_at_o1_p.html" ,MovieType.恐怖片},
                {"http://so.letv.com/list/c1_t19_a-1_y-1_f_at_o1_p.html" ,MovieType.动作片},
                {"http://so.letv.com/list/c1_t24_a-1_y-1_f_at_o1_p.html" ,MovieType.爱情片},
                {"http://so.letv.com/list/c1_t26_a-1_y-1_f_at_o1_p.html" ,MovieType.剧情片},
                {"http://so.letv.com/list/c1_t8_a_y_f_at_o_p.html", MovieType.剧情片}
            };

            var lst_2 = new Dictionary<string, TVType>
            {
                {"http://so.letv.com/list/c2_t-1_a1_y-1_f_at_o1_p.html", TVType.国产剧},    //大陆
                {"http://so.letv.com/list/c2_t-1_a2_y-1_f_at_o1_p.html", TVType.港台剧},    //香港
                {"http://so.letv.com/list/c2_t-1_a3_y-1_f_at_o1_p.html", TVType.港台剧},    //台湾
                {"http://so.letv.com/list/c2_t-1_a71_y-1_f_at_o1_p.html", TVType.欧美剧},   //美国
                {"http://so.letv.com/list/c2_t-1_a72_y-1_f_at_o1_p.html", TVType.欧美剧},   //英国
                {"http://so.letv.com/list/c2_t-1_a41_y-1_f_at_o1_p.html", TVType.日韩剧},   //日本
                {"http://so.letv.com/list/c2_t-1_a42_y-1_f_at_o1_p.html", TVType.日韩剧},   //韩国
                {"http://so.letv.com/list/c2_t-1_a101_y-1_f_at_o1_p.html", TVType.海外剧}   //海外[海外]
            };
            */
            #endregion

            #region 热播...[删]
            //List<MovieUrl> lst111 = new List<MovieUrl> { 
            //    new MovieUrl("http://so.letv.com/list/c1_t-1_a-1_y-1_f_at_o3_p.html", 1),     //1电影
            //    new MovieUrl("http://so.letv.com/list/c2_t-1_a-1_y-1_f_at_o3_p.html", 2),     //2电视剧
            //    new MovieUrl("http://so.letv.com/list/c3_t-1_a-1_y-1_f-1_at-1_o3_p.html", 3), //3动漫
            //    new MovieUrl("http://so.letv.com/list/c11_t-1_a-1_y_f_at_o3_p.html", 4),      //4综艺
            //    new MovieUrl("http://www.letv.com/vchannel/new_ch3_d1_p1.html", 5),           //5娱乐
            //    new MovieUrl("http://www.letv.com/vchannel/new_ch9_d1_p1.html", 6),           //6音乐
            //    new MovieUrl("http://www.letv.com/vchannel/new_ch16_d1_p1.html", 7)
            //};
            #endregion

            //最新
            List<MovieUrl> lst = new List<MovieUrl> { 
                new MovieUrl("http://so.letv.com/list/c1_t_a_y_f_at_o_p.html", 1),     //1电影
                new MovieUrl("http://so.letv.com/list/c2_t_a_y_f_at_o_p.html", 2),     //2电视剧
                new MovieUrl("http://so.letv.com/list/c3_t_a_y_f_at_o_p.html", 3),     //3动漫
                new MovieUrl("http://so.letv.com/list/c11_t_a_y_f_at_o_p.html", 4)     //4综艺
                //new MovieUrl("http://www.letv.com/vchannel/new_ch3_d1_p1.html", 5),    //5娱乐
                //new MovieUrl("http://www.letv.com/vchannel/new_ch9_d1_p1.html", 6),    //6音乐
                //new MovieUrl("http://www.letv.com/vchannel/new_ch16_d1_p1.html", 7)    //纪录片
            };

            Submit web = new Submit
            {
                Encode = Encoding.UTF8
            };

            string patt = @"<a href=""([^""]+?)"">([\d]+?)</a><a href=""[^""]+?"">下一页</a>";
            string maxPageUrl = "";
            int maxPage = 0;
            Match mch;

            for (int i = 0; i < lst.Count; i++)
            {
                Application.DoEvents();

                web.URL = lst[i].Url;
                try
                {
                    web.Get();
                    DoGet(web.Html, lst[i].Type);
                }
                catch (Exception)
                {
                    continue;
                }
                //continue;

                //计算页码，查找每页的url
                mch = Regex.Match(web.Html, patt);
                if (mch.Success)
                {
                    maxPageUrl = mch.Groups[1].Value;
                    maxPage = Convert.ToInt32(mch.Groups[2].Value);
                    for (int j = 2; j < 3; j++)
                    {
                        web = new Submit()
                        {
                            Encode = Encoding.UTF8,
                            URL = maxPageUrl.Replace(maxPage.ToString(), j.ToString())
                        };
                        try
                        {
                            web.Get();
                            DoGet(web.Html, lst[i].Type);
                        }
                        catch (Exception)
                        {
                            continue;
                        }
                    }
                }
            }
        }

        //DoGet
        private void DoGet(string html, int i)
        {
            switch (i)
            {
                case 1:
                    GetMovie(html, MovieType.未知);
                    break;
                case 2:
                    GetTv(html, TVType.未知);
                    break;
                case 3:
                    GetDm(html, i);
                    break;
                case 4:
                    GetZY(html, i);
                    break;
                case 5:
                case 6:
                case 7:
                    GetYL(html, i);
                    break;
            }
        }

        //movie
        private void GetMovie(string html, MovieType mt)
        {
            Match mch = Regex.Match(html, @"<dl class=""m_dl"">[^""]+?""([^""]+?)""[^""]+?""([^""]+?)"" target=""_blank""><img[^""]+?""([^""]+?)""[\s\S]+?主演([\s\S]+?)</dd>[\s\S]+?<i>([\d]\.[\d])</i>");
            while (mch.Success)
            {
                Application.DoEvents();
                Movie m = new Movie(SiteName)
                {
                    vod_cid = (int)mt,
                    vod_name = mch.Groups[2].Value.Replace("'", "‘"),
                    vod_pic = mch.Groups[3].Value,
                    vod_gold = mch.Groups[5].Value
                };

                if (m.Exist(m.vod_name))
                {
                    mch = mch.NextMatch();
                    continue;
                }

                //act
                string actors = "";
                Match mch2 = Regex.Match(mch.Groups[4].Value, @">([^<]+?)</a");
                while (mch2.Success)
                {
                    actors += " " + mch2.Groups[1].Value;
                    mch2 = mch2.NextMatch();
                }
                m.vod_actor = actors;
                m.vod_keywords += actors;

                //明细
                Submit web = new Submit()
                {
                    Encode = Encoding.UTF8,
                    URL = mch.Groups[1].Value
                };

                try
                {
                    web.Get();

                    if (!web.Html.Contains("点播购买"))
                    {
                        //0.类型
                        if (mt == MovieType.未知)
                        {
                            mch2 = Regex.Match(web.Html, @"id=""cate_info"">[^<]<a title=""([^""]+?)""");
                            if (mch2.Success)
                                m.vod_cid = GetMovieType(mch2.Groups[1].Value);
                        }

                        //1.年份
                        mch2 = Regex.Match(web.Html, @"年份：</b><a title=""([^""]+?)""");
                        if (mch2.Success)
                            m.vod_year = mch2.Groups[1].Value;

                        //2.地区
                        mch2 = Regex.Match(web.Html, @"地区：</b><a title=""([^""]+?)""");
                        if (mch2.Success)
                            m.vod_area = mch2.Groups[1].Value;

                        //3.简介
                        mch2 = Regex.Match(web.Html, @"<div id=""j-descript"">([\s\S]+?)</div>");
                        if (mch2.Success)
                            m.vod_content = mch2.Groups[1].Value.Replace("'", "‘");

                        //4.播放地址
                        m.vod_url = Movie.GetFlv(web.URL);
                        if (!string.IsNullOrEmpty(m.vod_url))
                        {
                            m.Insert(m);
                            OnMessage(this, string.Format("{0}Add Mv:{1}", Environment.NewLine, m.vod_name));
                        }
                        Thread.Sleep(100);
                    }
                }
                catch (Exception ee)
                {
                    OnMessage(this, string.Format("Mv Error:{0}", ee.Message));
                }

                mch = mch.NextMatch();
            }
        }

        //tv
        private void GetTv(string html, TVType tt)
        {
            //1
            Match mch = Regex.Match(html, @"<dl class=""m_dl"">[^""]+?""([^""]+?)""[^""]+?""([^""]+?)"" target=""_blank""><img[^""]+?""([^""]+?)""[\s\S]+?<i>[^\d]+?([\d]+?)集[全]?</i>[\s\S]+?主演([\s\S]+?)</dd>[\s\S]+?<i>([\d]\.[\d])</i>");
            while (mch.Success)
            {
                Application.DoEvents();
                Movie m = new Movie(SiteName)
                {
                    vod_cid = (int)tt,
                    vod_name = mch.Groups[2].Value.Replace("'", "‘"),
                    vod_pic = mch.Groups[3].Value,
                    vod_continu = Convert.ToInt32(mch.Groups[4].Value),
                    vod_gold = mch.Groups[6].Value
                };

                Match mch2;
                int vod_id = 0;
                int vod_continu = 0;
                bool bExist = m.Exist(m.vod_name, out vod_id, out vod_continu);
                m.vod_id = vod_id;

                if (bExist && (vod_continu == 0 || vod_continu == m.vod_continu))
                {
                    mch = mch.NextMatch();
                    continue;
                }

                //act
                if (!bExist)
                {
                    string actors = "";
                    mch2 = Regex.Match(mch.Groups[5].Value, @">([^<]+?)</a");
                    while (mch2.Success)
                    {
                        actors += " " + mch2.Groups[1].Value;
                        mch2 = mch2.NextMatch();
                    }
                    m.vod_actor = actors;
                    m.vod_keywords += actors;
                }

                //获得所有集的列表（一个片）
                Submit web = new Submit()
                {
                    Encode = Encoding.UTF8,
                    URL = mch.Groups[1].Value
                };

                //2
                try
                {
                    web.Get();

                    //年代 地区 简介
                    if (!bExist)
                    {
                        mch2 = Regex.Match(web.Html, @"<dl class=""textInfo"">[\s\S]+?国家/地区：[\s\S]+?>([^<]+?)</a>[\s\S]+?年代：[\s\S]+?>([^<]+?)</a>[\s\S]+?<p class=""p7"">([\s\S]+?)</p>");
                        if (mch2.Success)
                        {
                            m.vod_area = mch2.Groups[1].Value;
                            m.vod_year = mch2.Groups[2].Value;
                            m.vod_content = mch2.Groups[3].Value.Replace("'", "‘");
                            if (tt == TVType.未知)
                                m.vod_cid = GetTVType(m.vod_area);
                        }
                    }

                    //播放地址(一连串)
                    string pid = web.URL.Substring(web.URL.LastIndexOf("/") + 1).Replace(".html", "");
                    string flvAddr = "";
                    string flvAddrs = "";

                    //集
                    if (!bExist || (bExist && vod_continu > 0))
                    {
                        for (int i = vod_continu + 1; i < m.vod_continu + 1; i++)
                        {
                            flvAddr = Movie.GetFlv(string.Format("http://www.letv.com/ptv/pplay/{0}/{1}.html", pid, i));
                            if (string.IsNullOrEmpty(flvAddrs))
                                flvAddrs = flvAddr;
                            else
                                flvAddrs += Environment.NewLine + flvAddr;
                            Thread.Sleep(150);
                        }
                    }

                    m.vod_url = flvAddrs;
                    if (!bExist && !string.IsNullOrEmpty(m.vod_url))
                    {
                        m.Insert(m);
                        OnMessage(this, string.Format("{0}Add Tv:{1}", Environment.NewLine, m.vod_name));
                    }
                    if (bExist && !string.IsNullOrEmpty(m.vod_url))
                    {
                        m.UpdateUrl(m);
                        OnMessage(this, string.Format("{0}Update Tv:{1}", Environment.NewLine, m.vod_name));
                    }
                    Thread.Sleep(100);
                }
                catch (Exception ee)
                {
                    OnMessage(this, string.Format("Tv Error:{0}", ee.Message));
                }

                mch = mch.NextMatch();
            }
        }

        //dm
        private void GetDm(string html, int cid)
        {
            Match mch = Regex.Match(html, @"<dl class=""m_dl"">[^""]+?""([^""]+?)""[^""]+?""([^""]+?)"" target=""_blank""><img[^""]+?""([^""]+?)""[\s\S]+?<i>[^\d]+?([\d]+?)集[全]?</i>[\s\S]+?<i>([^<]+?)</i>");
            while (mch.Success)
            {
                Application.DoEvents();
                Movie m = new Movie(SiteName)
                {
                    vod_cid = cid,
                    vod_name = mch.Groups[2].Value.Replace("'", "‘"),
                    vod_pic = mch.Groups[3].Value,
                    vod_continu = Convert.ToInt32(mch.Groups[4].Value),
                    vod_gold = mch.Groups[5].Value
                };

                Match mch2;
                int vod_id = 0;
                int vod_continu = 0;
                bool bExist = m.Exist(m.vod_name, out vod_id, out vod_continu);
                m.vod_id = vod_id;

                if (bExist && (vod_continu == 0 || vod_continu == m.vod_continu))
                {
                    mch = mch.NextMatch();
                    continue;
                }

                //列表明细
                Submit web = new Submit()
                {
                    Encode = Encoding.UTF8,
                    URL = mch.Groups[1].Value
                };

                try
                {
                    web.Get();
                    string pid = web.URL.Substring(web.URL.LastIndexOf("/") + 1).Replace(".html", "");
                    string flvAddr = "";
                    string flvAddrs = "";

                    if (!bExist)
                    {
                        //年代
                        mch2 = Regex.Match(web.Html, @"年代：	<a href=""[^""]+?""target=""_blank"">([\d]+?)<");
                        if (mch2.Success)
                            m.vod_year = mch2.Groups[1].Value;

                        //介绍
                        mch2 = Regex.Match(web.Html, @"<meta name=""description"" content=""([^""]+?)""");
                        if (mch2.Success)
                            m.vod_content = mch2.Groups[1].Value.Replace("'", "‘");
                    }

                    if (!bExist || (bExist && vod_continu > 0))
                    {
                        for (int i = vod_continu + 1; i < m.vod_continu + 1; i++)
                        {
                            flvAddr = Movie.GetFlv(string.Format("http://www.letv.com/ptv/pplay/{0}/{1}.html", pid, i));
                            if (string.IsNullOrEmpty(flvAddrs))
                                flvAddrs = flvAddr;
                            else
                                flvAddrs += Environment.NewLine + flvAddr;
                            Thread.Sleep(150);
                        }
                    }

                    m.vod_url = flvAddrs;
                    if (!bExist && !string.IsNullOrEmpty(m.vod_url))
                    {
                        m.Insert(m);
                        OnMessage(this, string.Format("{0}Add Dm:{1}", Environment.NewLine, m.vod_name));
                    }
                    if (bExist && !string.IsNullOrEmpty(m.vod_url))
                    {
                        m.UpdateUrl(m);
                        OnMessage(this, string.Format("{0}Update Dm:{1}", Environment.NewLine, m.vod_name));
                    }
                    Thread.Sleep(100);
                }
                catch (Exception ee)
                {
                    OnMessage(this, string.Format("Dm Error:{0}", ee.Message));
                }

                mch = mch.NextMatch();
            }
        }

        //zy1
        private void GetZY(string html, int cid)
        {
            Match mch = Regex.Match(html, @"<dl class=""m_dl"">[^""]+?""([^""]+?)""[\s\S]+?主持人([\s\S]+?)</dd>");
            while (mch.Success)
            {
                Application.DoEvents();
                string pid = mch.Groups[1].Value.Substring(mch.Groups[1].Value.LastIndexOf("/") + 1).Replace(".html", "");

                #region 分析当前页
                string pageurl = string.Format("http://hot.vrs.letv.com/vlist?callback=LETV.App.Detail.List.paintList&y={0}&f=1&p=1&m=&pid={1}&b={2}&s=20&o=-1&_={3}"
                    , DateTime.Now.Year  //year
                    , pid     //pid
                    , "1"     //page 第一页
                    , Movie.GetMillTime(DateTime.Now));

                Submit web = new Submit()
                {
                    Encode = Encoding.UTF8,
                    URL = pageurl
                };
                try
                {
                    web.Get();
                    ParseZY(web.Html, cid);
                }
                catch (Exception ee)
                {
                    OnMessage(this, string.Format("Zy Error:{0}", ee.Message));
                }
                #endregion

                #region 分析其他页
                int counts = 0;
                int pages = 1;
                Match mch2 = Regex.Match(web.Html, @"count"":([^\,]+?)\,");
                if (mch2.Success)
                {
                    counts = int.Parse(mch2.Groups[1].Value);
                    pages = counts / 20 + counts % 20 > 0 ? 1 : 0;
                }

                pages = pages > 10 ? 15 : pages;
                for (int i = 2; i < pages + 1; i++)
                {
                    pageurl = string.Format("http://hot.vrs.letv.com/vlist?callback=LETV.App.Detail.List.paintList&y={0}&f=1&p=1&m=&pid={1}&b={2}&s=20&o=-1&_={3}"
                    , DateTime.Now.Year  //year
                    , pid     //pid
                    , i     //page
                    , Movie.GetMillTime(DateTime.Now));

                    try
                    {
                        web.Get();
                        ParseZY(web.Html, cid);
                    }
                    catch (Exception ee)
                    {
                        OnMessage(this, string.Format("Error:{0}", ee.Message));
                    }
                }
                #endregion

                mch = mch.NextMatch();
                Thread.Sleep(100);
            }
        }

        //zy2
        private void ParseZY(string html, int cid)
        {
            //地区
            Match mch = Regex.Match(html, @"area"":[^:]+?:""([^""]+?)""");
            string area = mch.Groups[1].Value;

            //分数
            mch = Regex.Match(html, @"rating"":""([^""]+?)""");
            string gold = mch.Groups[1].Value;

            //主持人
            mch = Regex.Match(html, @"starring"":""([^""]+?)""");
            string director = mch.Groups[1].Value;

            //XX卫视
            mch = Regex.Match(html, @"tvid"":""([^""]+?)""");
            string vid = mch.Groups[1].Value;

            mch = Regex.Match(html, @"actor"":""([^""]+?)"".*?name"":""([^""]+?)"".*?releasedate"":""([^""]+?)"",""subname"":""([^""]+?)"",""tag"":""([^""]+?)"",""url"":""([^""]+?)"",.*?viewPic"":""([^""]+?)""");
            while (mch.Success)
            {
                Movie m = new Movie(SiteName)
                {
                    vod_cid = cid,
                    vod_area = area,
                    vod_gold = gold,
                    vod_director = director,
                    vod_actor = mch.Groups[1].Value,
                    vod_name = mch.Groups[2].Value.Replace("'", "‘"),
                    vod_addtime = Movie.GetTime(mch.Groups[3].Value),
                    vod_keywords = mch.Groups[5].Value,
                    vod_content = string.Format("{0} {1} {2} {3}",
                        mch.Groups[2].Value,  //name
                        vid,
                        mch.Groups[4].Value,  //subname
                        mch.Groups[5].Value).Replace("'", "‘"), //keywords
                    vod_url = Movie.GetFlv(mch.Groups[6].Value),
                    vod_pic = mch.Groups[7].Value
                };

                if (!string.IsNullOrEmpty(m.vod_url) && !m.Exist(m.vod_name))
                {
                    m.Insert(m);
                    OnMessage(this, string.Format("{0}Add Zy:{1}", Environment.NewLine, m.vod_name));
                }
                Thread.Sleep(100);

                mch = mch.NextMatch();
            }
        }

        //yl
        private void GetYL(string html, int cid)
        {
            Match mch = Regex.Match(html, @"<dt><a target=""_blank"" title=""[^""]+?"" href=""([^""]+?)""><img alt=""([^""]+?)"" src=""([^""]+?)""></a></dt>[\s\S]+?时间：(.*?)</dd>");
            while (mch.Success)
            {
                Application.DoEvents();
                Movie m = new Movie(SiteName)
                {
                    vod_cid = cid,
                    vod_name = mch.Groups[2].Value.Replace("'", "‘"),
                    vod_pic = mch.Groups[3].Value,
                    vod_addtime = Movie.GetTime(mch.Groups[4].Value)
                };

                if (m.Exist(m.vod_name))
                {
                    mch = mch.NextMatch();
                    continue;
                }

                //播放页
                Submit web = new Submit()
                {
                    Encode = Encoding.UTF8,
                    URL = mch.Groups[1].Value
                };

                try
                {
                    web.Get();

                    //content
                    Match mch2 = Regex.Match(web.Html, @"<meta name=""description"" content=""([^""]+?)""");
                    if (mch2.Success)
                        m.vod_content = mch2.Groups[1].Value.Replace("'", "‘");

                    //4.播放地址
                    m.vod_url = Movie.GetFlv(web.URL);
                    if (!string.IsNullOrEmpty(m.vod_url))
                    {
                        m.Insert(m);
                        OnMessage(this, string.Format("{0}Add Other:{1}[{2}]", Environment.NewLine, m.vod_name, cid));
                    }
                    Thread.Sleep(150);
                }
                catch (Exception ee)
                {
                    OnMessage(this, string.Format("{0} Error:{1}", cid, ee.Message));
                }

                mch = mch.NextMatch();
            }
        }

        public int GetMovieType(string leMovieType)
        {
            MovieType mt = MovieType.剧情片;

            switch (leMovieType)
            {
                case "动作":
                case "犯罪":
                case "冒险":
                    mt = MovieType.动作片;
                    break;
                case "喜剧":
                    mt = MovieType.喜剧片;
                    break;
                case "爱情":
                case "伦理":
                    mt = MovieType.爱情片;
                    break;
                case "科幻":
                    mt = MovieType.科幻片;
                    break;
                case "恐怖":
                    mt = MovieType.恐怖片;
                    break;
                case "战争":
                    mt = MovieType.战争片;
                    break;
                case "剧情":
                case "家庭":
                    mt = MovieType.剧情片;
                    break;
            }

            return (int)mt;
        }

        public int GetTVType(string leTVType)
        {
            TVType tvType = TVType.海外剧;

            switch (leTVType)
            {
                case "中国大陆":
                case "大陆":
                    tvType = TVType.国产剧;
                    break;
                case "香港":
                case "台湾":
                case "中国香港":
                case "中国台湾":
                    tvType = TVType.港台剧;
                    break;
                case "美国":
                case "英国":
                    tvType = TVType.欧美剧;
                    break;
                case "日本":
                case "韩国":
                    tvType = TVType.日韩剧;
                    break;
                case "泰国":
                    tvType = TVType.海外剧;
                    break;
            }

            return (int)tvType;
        }

    }
}
